﻿using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using RabbitMQ.Client;

namespace Rmq.Center
{
    /// <summary>
    /// 收到消息的处理委托
    /// </summary>
    /// <param name="msgId">消息ID</param>
    /// <param name="receivedCount">消息已处理次数</param>
    /// <param name="msgProduceDt">消息生产时间</param>
    /// <param name="msg">消息体</param>
    /// <param name="channel">RMQ 消息管道</param>
    /// <returns>是否做出应答，应答表示消息处理完毕，不应答则重发消息，重发时可设置延时</returns>
    public delegate ConsumedResult ConsumerDelegate<in T>(Guid msgId, int receivedCount, DateTime msgProduceDt, T msg, WrapperChannel channel);

    public class WrapperChannel
    {
        private readonly IModel _channel;

        public WrapperChannel(IModel channel)
        {
            _channel = channel;
        }

        public void Publish<T>(T msg, string routingKey, int delayInMs = 0)
        {
            var wrappedMsg = new Msg<T>(msg);
            var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(wrappedMsg));
            if (delayInMs > 0)
            {
                var properties = _channel.CreateBasicProperties();
                properties.Persistent = true;
                properties.Headers = new Dictionary<string, object>();
                properties.Headers.Add("x-delay", delayInMs);

                _channel.BasicPublish(exchange: Const.DelayedExchangeName,
                    routingKey: routingKey,
                    basicProperties: properties,
                    body: body);
            }
            else
            {
                var properties = _channel.CreateBasicProperties();
                properties.Persistent = true;

                _channel.BasicPublish(exchange: Const.ExchangeName,
                    routingKey: routingKey,
                    basicProperties: properties,
                    body: body);
            }
        }
    }
}